package com.tencent.wxcloudrun.service;

import com.UpYun;
import com.tencent.wxcloudrun.utils.DateUtils;
import com.tencent.wxcloudrun.utils.FileKit;
import com.upyun.UpYunUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2023/2/19 13:47
 * @description: TODO
 */
@Service
public class UpYunStorage {
    public String writeToStore(byte[] bytes, String pathAndFileName) throws Exception {
        String domain = "https://image.lichongbing.com";
        String src = "/static/";

        if (StringUtils.isAnyBlank(domain)) {
            throw new Exception("请先在后台设置又拍云配置信息");
        }

        if (StringUtils.isBlank(src)) {
            src = "";
        } else {
            if (!src.startsWith("/")) {
                src = "/" + src;
            }

            if (!src.endsWith("/")) {
                src = src + "/";
            }
        }

        String key = UpYunUtils.md5(bytes);
        String time = DateUtils.getEndTime();
        src = src + time +"/";
        String suffix = FileKit.getSuffix(pathAndFileName);
        String i = String.valueOf(testSecureRandom());
        String path = src + i + ".png";
        UpYun upYun = builder();
        upYun.setContentMD5(key);
        upYun.writeFile(path, bytes, true);
        return domain.trim() + path;
    }

    public static int testSecureRandom() throws NoSuchAlgorithmException {
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(100000L);
        int i = secureRandom.nextInt(1000);
        return i;

    }


    public void deleteFile(String storePath) throws Exception {
        String domain = "http://image.lichongbing.com";
        String path = StringUtils.remove(storePath, domain.trim());
        UpYun yun = builder();
        try {
            yun.deleteFile(path);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
    private UpYun builder() throws Exception {
        String bucket = "lcbupayun";
        String operator = "admin";
        String password = "eg5BnwP1WHjzLWprl5tEVi0Fil8lVecY";

        if (StringUtils.isAnyBlank(bucket, operator, password)) {
            throw new Exception("请先在后台设置又拍云配置信息");
        }
        UpYun yun = new UpYun(bucket, operator, password);
        yun.setTimeout(60);
        yun.setApiDomain(UpYun.ED_AUTO);
        yun.setDebug(true);
        return yun;
    }
}
